package com.sgcc.activiti.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.sgcc.activiti.domain.*;
import com.sgcc.activiti.service.*;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.sgcc.common.log.annotation.Log;
import com.sgcc.common.log.enums.BusinessType;
import com.sgcc.common.security.annotation.PreAuthorize;
import com.sgcc.common.core.web.controller.BaseController;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.core.utils.poi.ExcelUtil;
import com.sgcc.common.core.web.page.TableDataInfo;

/**
 * 广告管理结果Controller
 *
 * @author sgcc
 * @date 2021-04-07
 */
@RestController
@RequestMapping("/OContentAd")
public class OContentAdController extends BaseController {
    @Autowired
    private IOContentAdService oContentAdService;
    @Autowired
    private IOContentAppService ioContentAppService;

    @Autowired
    private IOContentAdSchemaService ioContentAdSchemaService;

    @Autowired
    private IOContentAdPicService oContentAdPicService;

    @Autowired
    private IOInterfaceIndexService interfaceIndexService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private IOContentAppSchemaService oContentAppSchemaService;

    @Value("${isTest}")
    private Boolean isTest;

    /**
     * 查询广告管理结果列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:list")
    @GetMapping("/list")
    @Log(title = "查询广告列表", businessType = BusinessType.OTHER)
    public TableDataInfo list(OContentAd oContentAd) {
        startPage();
        List<OContentAd> list = oContentAdService.selectOContentAdList(oContentAd);
        return getDataTable(list);
    }

    /**
     * 导出广告管理结果列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:export")
    @Log(title = "广告管理结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OContentAd oContentAd) throws IOException {
        List<OContentAd> list = oContentAdService.selectOContentAdList(oContentAd);
        ExcelUtil<OContentAd> util = new ExcelUtil<OContentAd>(OContentAd.class);
        util.exportExcel(response, list, "OContentAd");
    }

    /**
     * 获取广告管理结果详细信息
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(oContentAdService.selectOContentAdById(id));
    }

    /**
     * 新增广告管理结果
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:add")
    @Log(title = "广告管理结果", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OContentAd oContentAd) {
        oContentAd = oContentAdService.insertOContentAd(oContentAd);
        if (null == oContentAd) {
            return AjaxResult.error("添加失败！");
        } else {
            return AjaxResult.success(oContentAd);
        }

    }

    /**
     * 修改广告管理结果
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:edit")
    @Log(title = "广告管理结果", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OContentAd oContentAd) {
        int i = oContentAdService.updateOContentAd(oContentAd);
        if (0 == i) {
            return AjaxResult.error("修改失败！");
        } else {
            return AjaxResult.success(oContentAd);
        }

    }

    /**
     * 删除广告管理结果
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAd:remove")
    @Log(title = "广告管理结果", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(oContentAdService.deleteOContentAdByIds(ids));
    }

    /**
     * 运营广告管理列表数据
     */
    @ResponseBody
    @RequestMapping(value = "/operationAdvertisingManagementData", method = RequestMethod.GET)
    @ApiOperation(notes = "operationAdvertisingManagementData", httpMethod = "POST", value = "查询运营广告管理列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "adState", value = "1：已上架  2：已下架", required = true, paramType = "query", dataType = "string")})
    // @ControllerLog(description = "查询运营广告管理列表数据", module = "内容管理模块", logType = LogType.ServiceType)
    public TableDataInfo operationAdvertisingManagementData(Integer pageNum,
                                                            Integer pageSize,
                                                            String adState) {

        OContentAd oContentAd = new OContentAd();
        oContentAd.setAdState(adState);
        return oContentAdService.operationAdvertisingManagementData(oContentAd, pageNum, pageSize);
    }

    /**
     * 获取广告banner位置
     */
    @ResponseBody
    @RequestMapping(value = "/getBannerAadsense", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sceneShow", value = "3 住宅   5 店铺  6 企事业", required = true, paramType = "query", dataType = "string")})
    public AjaxResult getBannerAadsense(String sceneShow) {
        List<ContentAdPosition> contentAdPositionList = oContentAdService.getBannerAadsense(sceneShow);
        return AjaxResult.success(contentAdPositionList);
    }


    /**
     * 广告发布
     */
    @ResponseBody
    @RequestMapping(value = "publish", method = RequestMethod.POST)
    @ApiOperation(notes = "publish", httpMethod = "POST", value = "广告发布")
//    @Log(title = "广告发布", businessType = BusinessType.OTHER)
    public AjaxResult publish(@RequestBody OContentAdSchema oContentAdSchemaDto, Model model) throws Exception {
        String id = oContentAdSchemaDto.getId();
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error(400, "缺少参数");
        }
        String serviceType1 = oContentAdSchemaDto.getServiceType();
        //广告banner图
        String bannerpicId = oContentAdSchemaDto.getBannerpicId();
        //广告详情图
        String advpoPicture = oContentAdSchemaDto.getAdvpoPicture();
        //广告小图
        String advUrl = oContentAdSchemaDto.getAdvUrl();

        OContentAdSchema oContentAdSchema = ioContentAdSchemaService.selectOContentAdSchemaById(id);
        String serviceType = oContentAdSchema.getServiceType();


        if (!DateUtils.isSameDay(new Date(),oContentAdSchema.getAdStartTime())) {
            return AjaxResult.error("广告开始时间应该是当天");
        }



        if (isTest) {
            //设置更变参数
            String isPublish = oContentAdSchemaDto.getIsPublish();
            String publishType = oContentAdSchemaDto.getPublishType();
            String advtypeId = oContentAdSchemaDto.getAdvtypeId();
            String adName = oContentAdSchemaDto.getAdName();
//				String bannerpicId = oContentAdSchemaDto.getBannerpicId();
//				String advpoPicture = oContentAdSchemaDto.getAdvpoPicture();
//				String advUrl = oContentAdSchemaDto.getAdvUrl();
            oContentAdSchema.setIsPublish(isPublish);
            oContentAdSchema.setPublishType(publishType);
            oContentAdSchema.setAdvtypeId(advtypeId);
            oContentAdSchema.setAdName(adName);
//				oContentAdSchema.setBannerpicId(bannerpicId);
//				oContentAdSchema.setAdvpoPicture(advpoPicture);
//				oContentAdSchema.setAdvUrl(advUrl);
            oContentAdSchema.setAdStartTime(oContentAdSchemaDto.getAdStartTime());
            oContentAdSchema.setAdEndTime(oContentAdSchemaDto.getAdEndTime());

            long time = System.currentTimeMillis();
            Date date1 = new Date(time);
//		OContentAdSchema oContentAdSchema = new OContentAdSchema();
//		BeanUtils.copyProperties(oContentAdSchemaDto, oContentAdSchema);
            // User user = UserUtils.getUser();
            HashMap<String, Object> var = new HashMap<>();
            String procInsId = oContentAdSchema.getProcInsId();
            String newId = oContentAdSchema.getNewId();

            oContentAdSchema.setAdvUrl(null);
            oContentAdSchema.setAdvpoPicture(null);
            oContentAdSchema.setBannerpicId(null);


            oContentAdSchema.setActName("结束");
            //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束
            oContentAdSchema.setFlowType("05");
            oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
            oContentAdSchema.setUpdateDate(new Date());
            oContentAdSchema.setSpareThree("true");
            ioContentAdSchemaService.updateOContentAdSchema(oContentAdSchema);

//            try {
//                processService.richProcessField(oContentAdSchema);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            JSONObject obj = new JSONObject();
//            obj.put("comment", "同意");
//            obj.put("pass", true);
//            obj.put("publishResults", "01");
//            obj.put("formData", oContentAdSchema);
//            processService.complete(oContentAdSchema.getTaskId(), oContentAdSchema.getInstanceId(), obj.toJSONString());

            return AjaxResult.success("广告发布成功!");

        }

        if ("01".equals(serviceType) || "02".equals(serviceType)) {
            //图片数据处理
            //picType 图片类型，01banner，02详情图片,03广告小图
            R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", bannerpicId, serviceType1, "01");
            if (adPic1.getCode() != 200) {
                return AjaxResult.error(adPic1.getMsg());
            }
            oContentAdSchema.setBannerpicId(adPic1.getData().getId());
            R<OContentAdPic> adPic2 = oContentAdPicService.uploadImg("02", advpoPicture, serviceType1, "01");
            if (adPic2.getCode() != 200) {
                return AjaxResult.error(adPic2.getMsg());
            }
            oContentAdSchema.setAdvpoPicture(adPic2.getData().getId());
            R<OContentAdPic> adPic3 = oContentAdPicService.uploadImg("03", advUrl, serviceType1, "01");
            if (adPic3.getCode() != 200) {
                return AjaxResult.error(adPic3.getMsg());
            }
            oContentAdSchema.setAdvUrl(adPic3.getData().getId());
        }

        //设置更变参数
        String isPublish = oContentAdSchemaDto.getIsPublish();
        String publishType = oContentAdSchemaDto.getPublishType();
        String advtypeId = oContentAdSchemaDto.getAdvtypeId();
        String adName = oContentAdSchemaDto.getAdName();
//				String bannerpicId = oContentAdSchemaDto.getBannerpicId();
//				String advpoPicture = oContentAdSchemaDto.getAdvpoPicture();
//				String advUrl = oContentAdSchemaDto.getAdvUrl();
        oContentAdSchema.setIsPublish(isPublish);
        oContentAdSchema.setPublishType(publishType);
        oContentAdSchema.setAdvtypeId(advtypeId);
        oContentAdSchema.setAdName(adName);
//				oContentAdSchema.setBannerpicId(bannerpicId);
//				oContentAdSchema.setAdvpoPicture(advpoPicture);
//				oContentAdSchema.setAdvUrl(advUrl);
        oContentAdSchema.setAdStartTime(oContentAdSchemaDto.getAdStartTime());
        oContentAdSchema.setAdEndTime(oContentAdSchemaDto.getAdEndTime());

        long time = System.currentTimeMillis();
        Date date1 = new Date(time);
//		OContentAdSchema oContentAdSchema = new OContentAdSchema();
//		BeanUtils.copyProperties(oContentAdSchemaDto, oContentAdSchema);
        // User user = UserUtils.getUser();
        HashMap<String, Object> var = new HashMap<>();
        String procInsId = oContentAdSchema.getProcInsId();
        String newId = oContentAdSchema.getNewId();

        /**
         * 调用发布接口
         */
        String callBackResult = "";
        int resultCode = 0;
        String message = "";
        String newId2 = "";
//        String rpcInterface = "test";
        if ("01".equals(serviceType)) {
            //发布接口调用
            // rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
            OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101202");
            if (oInterfaceIndex == null || oInterfaceIndex.getInterfaceAdress() == null) {
                return AjaxResult.error("无法根据0101202获得接口");
            }
            String params = "";
            //构建参数
            /**
             * {
             *  "serviceCode": "0101202",
             *  "source": "01",
             *  "target": "33101",
             *  "data":{
             *   "serialNum":"a1a1a121221a1",
             *   "serviceType":"广告发布",
             *   "platformId":"330000",
             *   "releaseScope":"330000",
             *   "advBannerId":"001a3de7edd247fb9984fc8752689772",
             *   "publishType":"1",
             *   "advPoPicture":"",
             *   "sceneShow":"5",
             *   "advPositionName":"276",
             *   "adName":"001a3de7edd247fb9984fc8752689772",
             *   "isPublish":"0",
             *   "advTypeId":"静态图片",
             *   "startTime":"2018-11-26 20:30:05",
             *   "endTime":"2018-11-29 20:59:59"
             *   }
             * }
             */
            OContentAdPic oContentAdPic1 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getBannerpicId());
            OContentAdPic oContentAdPic2 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getAdvpoPicture());
            OContentAdPic oContentAdPic3 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getAdvUrl());
            Map paramsData = new HashMap();
            paramsData.put("serialNum", oContentAdSchema.getId());//序列号:省侧生成唯一标识
            paramsData.put("serviceType", oContentAdSchema.getServiceType());//业务类型:业务类型
            paramsData.put("platformId", "350000");//网省平台ID:网省平台ID
            paramsData.put("releaseScope", "350000");//省份编码:网省编号
            paramsData.put("advBannerId", oContentAdPic1.getPicId());//广告banner图ID:图片id(服务连接平台返回的id)
            paramsData.put("publishType", oContentAdSchema.getPublishType());//应用类型:1.图片 2.微应用 3.链接地址 4.无链接
            paramsData.put("advPoPicture", oContentAdPic2.getPicId());//广告详情图:链接地址/图片地址/微应用链接如果是广告类型为1，传服务连接平台返回id；如果广告类型为2，传移动交互平台返回的微应用编码。
            paramsData.put("sceneShow", oContentAdSchema.getSceneShow());//展示场景:3 住宅 5 店铺 6 企事业
            paramsData.put("advPositionName", oContentAdSchema.getAdvPositionName());//banner位置:276 banner2  277 banner3
            paramsData.put("adName", oContentAdSchema.getAdName());//广告名称:广告名称
            paramsData.put("isPublish", oContentAdSchema.getIsPublish());//是否立即发布:是否及时发布0 按时间   1 立即
            paramsData.put("advTypeId", oContentAdSchema.getAdvtypeId());//广告类型:1.静态图片
            paramsData.put("startTime", DateUtils.convertToString(oContentAdSchema.getAdStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));//广告发布时间:发布时间 yyyy-MM-dd HH:mm:ss，发布时间应该传当前日期
            paramsData.put("endTime", DateUtils.convertToString(oContentAdSchema.getAdEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));//广告结束时间:结束时间 yyyy-MM-dd HH:mm:ss，结束时间需大于开始时间
            paramsData.put("advBannerMiddleUrl", oContentAdPic3.getPicId());//广告小图:广告图对应的小尺寸图片

            Map map = new HashMap();
            map.put("serviceCode", "0101202");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);
            params = FastJsonUtil.toJSONString(map);
            R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
            if (200 != rpcResultStr.getCode()) {
                return AjaxResult.error(oInterfaceIndex.getInterfaceAdress() + "接口调用失败！" + rpcResultStr.getCode());
            }
            //解析返回值
            R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
            resultCode = r.getCode();
//            if (resultCode == 1) {
//                JSONObject data = (JSONObject) r.getData();
//                /**
//                 * 判断回调返回值
//                 */
//                OContentAd condition = new OContentAd();
//                condition.setNewId(oContentAdSchema.getNewId());
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
//                OContentAd callBackAd = list.get(0);
//                callBackResult = callBackAd.getSpareFive();
//                if (StringUtils.isNotBlank(callBackResult)) {
//                    String[] split = callBackResult.split(":");
//                    resultCode = Integer.valueOf(split[0]);
//                    message = split[1];
//                } else {
//                    long callBackFlag = 0;
//                    long callBackTimes = Long.valueOf(10);
//                    while (callBackFlag < callBackTimes) {
//                        callBackFlag++;
//                        OContentAd condition2 = new OContentAd();
//                        condition2.setNewId(oContentAdSchema.getNewId());
//                        List<OContentAd> list2 = oContentAdService.selectOContentAdList(condition2);
//                        OContentAd callBackAd2 = list2.get(0);
//                        callBackResult = callBackAd2.getSpareFive();
//                        if (StringUtils.isNotBlank(callBackResult)) {
//                            String[] split2 = callBackResult.split(":");
//                            resultCode = Integer.valueOf(split2[0]);
//                            message = split2[1];
//                            callBackFlag = callBackTimes;
//                        } else {
//                            Thread.sleep(1000L);
//                        }
//                    }
//                }
//                if (StringUtils.isBlank(callBackResult)) {
//                    return AjaxResult.error("远程系统没有调用回调接口");
//                }
//            }

        } else if ("02".equals(serviceType)) {
            //更新接口调用
            // rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
            OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101203");
            if (oInterfaceIndex == null || oInterfaceIndex.getInterfaceAdress() == null) {
                return AjaxResult.error("无法根据0101203获得接口");
            }
            String params = "";
            //构建参数
            /**
             * {
             *  "serviceCode":"0101203",
             *  "target":"33101",
             *  "source":"01",
             *  "data":{
             *    "serialNum":"qwr223423dsds233f2w23e",
             *    "serviceType":"qedqwdwefwsdfw",
             *    "platformId":"330000",
             *    "releaseScope":"330000",
             *    "adId":"2d6ea3c64b654fb68a681c748def25b2",
             *    "advBannerId":"001a3de7edd247fb9984fc8752689772",
             *    "publishType":"2",
             *    "isPublish":"0",
             *    "advTypeId":"1",
             *    "advPoPicture":"7a03524f-208d-451e-a702-ac86ca9157ed",
             *    "sceneShow":"3",
             *    "advPositionName":"287",
             *    "adName":"1234",
             *    "startTime":"2019-05-05 10:30:05",
             *    "endTime":"2019-05-05 20:59:59"
             *  }
             * }
             */
            OContentAdPic oContentAdPic1 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getBannerpicId());
            OContentAdPic oContentAdPic2 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getAdvpoPicture());
            OContentAdPic oContentAdPic3 = oContentAdPicService.selectOContentAdPicById(oContentAdSchema.getAdvUrl());
            Map paramsData = new HashMap();
            paramsData.put("serialNum", oContentAdSchema.getId());//序列号:省侧生成唯一标识
            paramsData.put("serviceType", "02");//业务类型:业务类型
            paramsData.put("platformId", "350000");//网省平台ID:网省平台ID
            paramsData.put("releaseScope", "350000");//省份编码:网省编号
            paramsData.put("adId", oContentAdSchema.getNewId());//省份编码:网省编号
            paramsData.put("advBannerId", oContentAdPic1.getPicId());//广告banner图ID:图片id(服务连接平台返回的id)
            paramsData.put("publishType", oContentAdSchema.getPublishType());//应用类型:1.图片 2.微应用 3.链接地址 4.无链接
            paramsData.put("advPoPicture", oContentAdPic2.getPicId());//广告详情图:链接地址/图片地址/微应用链接如果是广告类型为1，传服务连接平台返回id；如果广告类型为2，传移动交互平台返回的微应用编码。
            paramsData.put("sceneShow", oContentAdSchema.getSceneShow());//展示场景:3 住宅 5 店铺 6 企事业
            paramsData.put("advPositionName", oContentAdSchema.getAdvPositionName());//banner位置:276 banner2  277 banner3
            paramsData.put("adName", oContentAdSchema.getAdName());//广告名称:广告名称
            paramsData.put("isPublish", oContentAdSchema.getIsPublish());//是否立即发布:是否及时发布0 按时间   1 立即
            paramsData.put("advTypeId", oContentAdSchema.getAdvtypeId());//广告类型:1.静态图片
            paramsData.put("startTime", DateUtils.convertToString(oContentAdSchema.getAdStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));//广告发布时间:发布时间 yyyy-MM-dd HH:mm:ss，发布时间应该传当前日期
            paramsData.put("endTime", DateUtils.convertToString(oContentAdSchema.getAdEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));//广告结束时间:结束时间 yyyy-MM-dd HH:mm:ss，结束时间需大于开始时间
            paramsData.put("advBannerMiddleUrl", oContentAdPic3.getPicId());//广告小图:广告图对应的小尺寸图片
                /*CommonParm commonParm = new CommonParm();
                commonParm.setTarget("35101");
                commonParm.setSource("SGAPP");
                commonParm.setServiceCode("0101203");
                commonParm.setData(paramsData);
                params = FastJsonUtil.toJSONString(commonParm);*/
            Map map = new HashMap();
            map.put("serviceCode", "0101203");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);
            params = FastJsonUtil.toJSONString(map);
            R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
            //解析返回值
            if (rpcResultStr.getCode() != 200) {
                return AjaxResult.error(oInterfaceIndex.getInterfaceAdress() + "接口调用失败！" + rpcResultStr.getCode());
            }
            R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
            resultCode = r.getCode();
            message = r.getMsg();
//            if (resultCode == 1) {
//                JSONObject data = (JSONObject) r.getData();
//                /**
//                 * 判断回调返回值
//                 */
//                OContentAd condition = new OContentAd();
//                condition.setNewId(oContentAdSchema.getNewId());
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
//                OContentAd callBackAd = list.get(0);
//                callBackResult = callBackAd.getSpareFive();
//                if (StringUtils.isNotBlank(callBackResult)) {
//                    String[] split = callBackResult.split(":");
//                    resultCode = Integer.valueOf(split[0]);
//                    message = split[1];
//                } else {
//                    long callBackFlag = 0;
//                    long callBackTimes = Long.valueOf(10);
//                    while (callBackFlag < callBackTimes) {
//                        callBackFlag++;
//                        OContentAd condition2 = new OContentAd();
//                        condition2.setNewId(oContentAdSchema.getNewId());
//                        List<OContentAd> list2 = oContentAdService.selectOContentAdList(condition2);
//                        OContentAd callBackAd2 = list2.get(0);
//                        callBackResult = callBackAd2.getSpareFive();
//                        if (StringUtils.isNotBlank(callBackResult)) {
//                            String[] split2 = callBackResult.split(":");
//                            resultCode = Integer.valueOf(split2[0]);
//                            message = split2[1];
//                            callBackFlag = callBackTimes;
//                        } else {
//                            Thread.sleep(1000L);
//                        }
//                    }
//                }
//                if (StringUtils.isBlank(callBackResult)) {
//                    return AjaxResult.error("远程系统没有调用回调接口");
//                }
//            }
        } else if ("03".equals(serviceType)) {
            //更新接口调用
            // rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
            OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101204");
            if (oInterfaceIndex == null || oInterfaceIndex.getInterfaceAdress() == null) {
                return AjaxResult.error("无法根据0101204获得接口");
            }
            String params = "";
            //构建参数
            Map paramsData = new HashMap();
            paramsData.put("serialNum", oContentAdSchema.getId());//序列号:省侧生成唯一标识
            paramsData.put("serviceType", "03");//业务类型:业务类型
            paramsData.put("platformId", "350000");//网省平台ID:网省平台ID
            paramsData.put("releaseScope", "350000");//省份编码:网省编号
            paramsData.put("adId", oContentAdSchema.getNewId());//
            Map map = new HashMap();
            map.put("serviceCode", "0101204");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);
            params = FastJsonUtil.toJSONString(map);
            R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
            //解析返回值
            if (rpcResultStr.getCode() != 200) {
                return AjaxResult.error(oInterfaceIndex.getInterfaceAdress() + "接口调用失败！" + rpcResultStr.getCode());
            }
            R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
            resultCode = r.getCode();
            message = r.getMsg();
//            if (resultCode == 1) {
//                JSONObject data = (JSONObject) r.getData();
//                /**
//                 * 判断回调返回值
//                 */
//                OContentAd condition = new OContentAd();
//                condition.setNewId(oContentAdSchema.getNewId());
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
//                OContentAd callBackAd = list.get(0);
//                callBackResult = callBackAd.getSpareFive();
//                if (StringUtils.isNotBlank(callBackResult)) {
//                    String[] split = callBackResult.split(":");
//                    resultCode = Integer.valueOf(split[0]);
//                    message = split[1];
//                } else {
//                    long callBackFlag = 0;
//                    long callBackTimes = Long.valueOf(10);
//                    while (callBackFlag < callBackTimes) {
//                        callBackFlag++;
//                        OContentAd condition2 = new OContentAd();
//                        condition2.setNewId(oContentAdSchema.getNewId());
//                        List<OContentAd> list2 = oContentAdService.selectOContentAdList(condition2);
//                        OContentAd callBackAd2 = list2.get(0);
//                        callBackResult = callBackAd2.getSpareFive();
//                        if (StringUtils.isNotBlank(callBackResult)) {
//                            String[] split2 = callBackResult.split(":");
//                            resultCode = Integer.valueOf(split2[0]);
//                            message = split2[1];
//                            callBackFlag = callBackTimes;
//                        } else {
//                            Thread.sleep(1000L);
//                        }
//                    }
//                }
//                if (StringUtils.isBlank(callBackResult)) {
//                    return AjaxResult.error("远程系统没有调用回调接口");
//                }
//            }
        }
        oContentAdSchema.setAdvUrl(null);
        oContentAdSchema.setAdvpoPicture(null);
        oContentAdSchema.setBannerpicId(null);
        if (resultCode != 1) {
            //发布失败
            //编辑表单
            // 当前环节，包括流程的环节，有结束、终止等
            oContentAdSchema.setSpareTwo(message);
            oContentAdSchema.setActName("发布失败");
            //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束
            oContentAdSchema.setFlowType("04");
            oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
            ioContentAdSchemaService.updateOContentAdSchema(oContentAdSchema);
            try {
                processService.richProcessField(oContentAdSchema);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject obj = new JSONObject();
            obj.put("comment", "发布失败");
            obj.put("pass", false);
            obj.put("publishResults", "02");
            obj.put("formData", oContentAdSchema);
            processService.complete(oContentAdSchema.getTaskId(), oContentAdSchema.getInstanceId(), obj.toJSONString());
            return AjaxResult.error("广告流程发布失败!");
        } else {
            //发布成功
            //编辑表单
            // 当前环节，包括流程的环节，有结束、终止等
            oContentAdSchema.setActName("结束");
            //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束
            oContentAdSchema.setFlowType("05");
            oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
            if ("01".equals(serviceType) && resultCode == 1) {
                oContentAdSchema.setSpareOne(newId2);
            }
            ioContentAdSchemaService.updateOContentAdSchema(oContentAdSchema);

//            try {
//                processService.richProcessField(oContentAdSchema);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            JSONObject obj = new JSONObject();
//            obj.put("comment", "同意");
//            obj.put("pass", true);
//            obj.put("publishResults", "01");
//            obj.put("formData", oContentAdSchema);
//            processService.complete(oContentAdSchema.getTaskId(), oContentAdSchema.getInstanceId(), obj.toJSONString());
            return AjaxResult.success("广告发布成功!");
        }
    }

    /**
     * 回调接口
     */
    @ResponseBody
//	@RequiresPermissions("goshine:ocontentad:oContentAd:list")
    @PostMapping(value = "/callBack")
//    @ApiOperation(notes = "callBack", httpMethod = "POST", value = "回调接口")
    @Log(title = "回调接口", businessType = BusinessType.UPDATE)
//    @RequestBody
    public Map<String, Object> callBack(@RequestBody CommonParm callBackParm) {
        logger.info("广告咨询回调接口:" + JSONObject.toJSONString(callBackParm));
        Map parmData = net.sf.json.JSONObject.fromObject(callBackParm.getData());
        //状态码 0 失败   1 成功
        String code = (String) parmData.get("code");
        //状态信息
        String message = (String) parmData.get("message");
        //服务编码 广告发布 0101202 ； 广告变更 0101203 ； 广告下线 0101204
        String srvCode = (String) parmData.get("srvCode");
        //序列号 自定义newId
        String serialNum = (String) parmData.get("serialNum");
        //newId
        String newId = (String) parmData.get("newId");

        //服务类型 01:广告发布  ； 02:广告变更  ； 03:广告下线 ； 04:资讯发布 ； 05:资讯修改 ；06:资讯下架 ；
        String serviceType = (String) parmData.get("serviceType");

        //回调结果
        String callBackResult = code + ":" + message;
        if ("1".equals(code)) {
            //成功

            if ("01".equals(serviceType)) {
                //广告发布(新增)
                if (StringUtils.isNotBlank(serialNum)) {
                    OContentAdSchema condition = ioContentAdSchemaService.selectOContentAdSchemaById(serialNum);
//                    OContentAd condition = oContentAdService.selectOContentAdSchemaById(serialNum);
//                    condition.setNewId(serialNum);
//                    List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
//                    if (list.size() > 0 && null != list.get(0)) {
                    if (null != condition) {
                        condition.setNewId(newId);
                        condition.setSpareFive(callBackResult);
//                        oContentAdService.insertOContentAd(condition);
                        ioContentAdSchemaService.updateOContentAdSchema(condition);

                        OContentAd oContentAd = oContentAdService.selectOContentAdById(condition.getAppNo());
                        oContentAd.setBannerpicId(condition.getBannerpicId());
                        oContentAd.setAdName(condition.getAdName());
                        oContentAd.setSceneShow(condition.getSceneShow());
                        oContentAd.setAdvPositionName(condition.getAdvPositionName());
                        oContentAd.setAdvpoPicture(condition.getAdvpoPicture());
                        oContentAd.setAdvtypeId(condition.getAdvtypeId());
                        oContentAd.setPublishType(condition.getPublishType());
                        oContentAd.setAdStartTime(condition.getAdStartTime());
                        oContentAd.setAdEndTime(condition.getAdEndTime());
                        oContentAd.setAdvUrl(condition.getAdvUrl());
                        oContentAd.setUpdateTime(new Date());
                        oContentAd.setSpareOne(newId);
                        oContentAd.setNewId(newId);
                        oContentAdService.updateOContentAd(oContentAd);

                        try {
                            processService.richProcessField(condition);
                            JSONObject obj = new JSONObject();
                            obj.put("comment", "同意");
                            obj.put("pass", true);
                            obj.put("publishResults", "01");
                            obj.put("formData", condition);
                            processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else if ("02".equals(serviceType) || "03".equals(serviceType)) {
                //广告变更&广告下线(变更&下架) =》 newId不变
                if (StringUtils.isNotBlank(serialNum)) {
//                    OContentAd condition = oContentAdService.selectOContentAdByNewId(newId);
                    OContentAdSchema condition = ioContentAdSchemaService.selectOContentAdSchemaById(serialNum);
//                    OContentAd condition = new OContentAd();
//                    condition.setNewId(serialNum);
//                    List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
//                    if (list.size() > 0 && null != list.get(0)) {
                    if (null != condition) {
                        OContentAd oContentAd = oContentAdService.selectOContentAdByNewId(newId);
                        oContentAd.setSpareOne(newId);
                        if ("02".equals(serviceType)) {
                            oContentAd.setBannerpicId(condition.getBannerpicId());
                            oContentAd.setAdName(condition.getAdName());
                            oContentAd.setSceneShow(condition.getSceneShow());
                            oContentAd.setAdvPositionName(condition.getAdvPositionName());
                            oContentAd.setAdvpoPicture(condition.getAdvpoPicture());
                            oContentAd.setAdvtypeId(condition.getAdvtypeId());
                            oContentAd.setPublishType(condition.getPublishType());
                            oContentAd.setAdStartTime(condition.getAdStartTime());
                            oContentAd.setAdEndTime(condition.getAdEndTime());
                            oContentAd.setAdvUrl(condition.getAdvUrl());
                            oContentAd.setUpdateTime(new Date());
                            oContentAd.setSpareOne(newId);
                        } else {
                            oContentAd.setAdState("2");
                            oContentAd.setSpareTwo(newId);
                        }
                        oContentAdService.updateOContentAd(oContentAd);

                        condition.setSpareFive(callBackResult);
                        ioContentAdSchemaService.updateOContentAdSchema(condition);
                        try {
                            processService.richProcessField(condition);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        JSONObject obj = new JSONObject();
                        obj.put("comment", "同意");
                        obj.put("pass", true);
                        obj.put("publishResults", "01");
                        obj.put("formData", condition);
                        processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                    }
                }
            } else if ("04".equals(serviceType)) {//资讯新增
                if (StringUtils.isNotBlank(serialNum)) {
                    OContentAppSchema condition = oContentAppSchemaService.selectOContentAppSchemaById(serialNum);
                    if (null != condition) {
                        condition.setRemarks(callBackResult);
                        condition.setNewId(newId);
                        oContentAppSchemaService.updateOContentAppSchema(condition);
                        OContentApp oContentApp = ioContentAppService.selectOContentAppById(condition.getAppId());
                        oContentApp.setNewId(newId);
                        oContentApp.setContentTitle(condition.getContentTitle());
                        oContentApp.setContentScene(condition.getContentScene());
                        oContentApp.setContentDetails(condition.getContentDetails());
                        oContentApp.setReleaseScope(condition.getReleaseScope());
                        oContentApp.setContentinFormtion(condition.getContentinFormtion());
                        oContentApp.setContentAuthor(condition.getContentAuthor());
                        oContentApp.setMationType(condition.getMationType());
                        oContentApp.setPublishType(condition.getPublishType());
                        oContentApp.setBannerpicId(condition.getBannerpicId());
                        oContentApp.setContentPicids(condition.getContentPicids());
                        oContentApp.setContentApp(condition.getContentApp());
                        oContentApp.setServiceType(condition.getServiceType());
                        oContentApp.setRemarks(condition.getRemarks());
                        ioContentAppService.updateOContentApp(oContentApp);

                        try {
                            processService.richProcessField(condition);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        JSONObject obj = new JSONObject();
                        obj.put("comment", "同意");
                        obj.put("pass", true);
                        obj.put("publishResults", "01");
                        obj.put("formData", condition);
                        processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                    }
                }
            } else if ("05".equals(serviceType) || "06".equals(serviceType)) {
                if (StringUtils.isNotBlank(serialNum)) {
                    OContentAppSchema condition = oContentAppSchemaService.selectOContentAppSchemaById(serialNum);
//                OContentAd condition = new OContentAd();
//                condition.setNewId(serialNum);
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
                    if (null != condition) {
                        OContentApp oContentApp = ioContentAppService.selectOContentAppById(condition.getAppId());
                        if ("05".equals(serviceType)) {
                            oContentApp.setContentTitle(condition.getContentTitle());
                            oContentApp.setContentScene(condition.getContentScene());
                            oContentApp.setContentDetails(condition.getContentDetails());
                            oContentApp.setReleaseScope(condition.getReleaseScope());
                            oContentApp.setContentinFormtion(condition.getContentinFormtion());
                            oContentApp.setContentAuthor(condition.getContentAuthor());
                            oContentApp.setMationType(condition.getMationType());
                            oContentApp.setPublishType(condition.getPublishType());
                            oContentApp.setBannerpicId(condition.getBannerpicId());
                            oContentApp.setContentPicids(condition.getContentPicids());
                            oContentApp.setContentApp(condition.getContentApp());
                            oContentApp.setServiceType(condition.getServiceType());
                            oContentApp.setRemarks(condition.getRemarks());
                        } else {
                            oContentApp.setAdvissueState("2");
                        }
                        ioContentAppService.updateOContentApp(oContentApp);

                        condition.setRemarks(callBackResult);
                        oContentAppSchemaService.updateOContentAppSchema(condition);
                        try {
                            processService.richProcessField(condition);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        JSONObject obj = new JSONObject();
                        obj.put("comment", "同意");
                        obj.put("pass", true);
                        obj.put("publishResults", "01");
                        obj.put("formData", condition);
                        processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                    }
                }
            }
        } else {
            //失败
            if (StringUtils.isNotBlank(serialNum) && ("01".equals(serviceType) || "02".equals(serviceType) || "03".equals(serviceType))) {
                OContentAdSchema condition = ioContentAdSchemaService.selectOContentAdSchemaById(serialNum);
//                OContentAd condition = new OContentAd();
//                condition.setNewId(serialNum);
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
                if (null != condition) {
//                    OContentAd oContentAd = list.get(0);
                    condition.setSpareFive(callBackResult);
                    ioContentAdSchemaService.updateOContentAdSchema(condition);
                    try {
                        processService.richProcessField(condition);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("comment", "发布失败");
                    obj.put("pass", true);
                    obj.put("publishResults", "02");
                    obj.put("formData", condition);
                    processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                }
            } else {

                OContentAppSchema condition = oContentAppSchemaService.selectOContentAppSchemaById(serialNum);
//                OContentAd condition = new OContentAd();
//                condition.setNewId(serialNum);
//                List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
                if (null != condition) {
//                    OContentAd oContentAd = list.get(0);
                    condition.setRemarks(callBackResult);
                    oContentAppSchemaService.updateOContentAppSchema(condition);
                    try {
                        processService.richProcessField(condition);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("comment", "发布失败");
                    obj.put("pass", true);
                    obj.put("publishResults", "02");
                    obj.put("formData", condition);
                    processService.complete(condition.getTaskId(), condition.getInstanceId(), obj.toJSONString());
                }
            }
        }
        //构造返回数据
        Map result = new HashMap();
        ContentAdCommonResult data = new ContentAdCommonResult();
        data.setRtnCode("1");
        data.setRtnMsg("成功");
        result.put("data", data);
        return result;
    }

}
